import { ref, reactive, computed, type Ref, onMounted } from "vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { cloneDeep } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import type { PaginationProps } from "@pureadmin/table";
import editForm from "../form/index.vue";
import type {
  EventItem,
  TriggerConditionItem,
  ExecuteActionItem
} from "./types";

// 事件列表列配置
const eventListColumns = [
  { label: "勾选列", type: "selection", fixed: "left", reserveSelection: true },
  { label: "ID", prop: "id", width: 90 },
  { label: "名称", prop: "name", minWidth: 130 },
  { label: "租户ID", prop: "tenantId", minWidth: 90 },
  { label: "租户名称", prop: "tenantName", minWidth: 130 },
  { label: "经销商ID", prop: "dealerId", minWidth: 90 },
  { label: "经销商名称", prop: "dealerName", minWidth: 130 },
  { label: "备注", prop: "remark", minWidth: 130 },
  {
    label: "状态",
    prop: "status",
    minWidth: 90,
    formatter: (row: any) => (row.status === 1 ? "已启用" : "已禁用")
  },
  { label: "操作", fixed: "right", width: 180, slot: "operation" }
];

// 触发条件列配置
const triggerConditionsColumns = [
  { label: "勾选列", type: "selection", fixed: "left", reserveSelection: true },
  { label: "ID", prop: "id", width: 90 },
  { label: "事件ID", prop: "eventId", minWidth: 90 },
  { label: "事件名称", prop: "eventName", minWidth: 130 },
  { label: "条件", prop: "condition", minWidth: 130 },
  { label: "操作符", prop: "operator", minWidth: 90 },
  { label: "参数", prop: "params", minWidth: 130 },
  { label: "操作", fixed: "right", width: 180, slot: "operation" }
];

// 执行动作列配置
const executeActionsColumns = [
  { label: "勾选列", type: "selection", fixed: "left", reserveSelection: true },
  { label: "ID", prop: "id", width: 90 },
  { label: "事件ID", prop: "eventId", minWidth: 90 },
  { label: "事件名称", prop: "eventName", minWidth: 130 },
  { label: "动作", prop: "action", minWidth: 130 },
  { label: "参数", prop: "params", minWidth: 130 },
  { label: "操作", fixed: "right", width: 180, slot: "operation" }
];

export function useEventManage(tableRef: Ref) {
  const form = reactive({
    eventName: "",
    eventId: "",
    status: "",
    SearchTerm: "",
    OrderBy: ""
  });

  //const formRef = ref();
  const loading = ref(true);
  const selectedNum = ref(0);

  // 三个标签页的数据
  const dataList = ref<
    [EventItem[], TriggerConditionItem[], ExecuteActionItem[]]
  >([[], [], []]);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 三个标签页的列配置
  const columns = [
    eventListColumns,
    triggerConditionsColumns,
    executeActionsColumns
  ];

  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });

  // 搜索
  function onSearch() {
    loading.value = true;
    const activeTab = ref(0);
    // 根据当前选中的标签页加载不同的数据
    switch (activeTab.value) {
      case 0:
        loadEventList();
        break;
      case 1:
        loadTriggerConditions();
        break;
      case 2:
        loadExecuteActions();
        break;
    }
  }

  // 加载事件列表
  function loadEventList() {
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm
    };

    http
      .post(changeHttpLink("/api/Event"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value[0] = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 加载触发条件
  function loadTriggerConditions() {
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm
    };

    http
      .post(changeHttpLink("/api/Event/TriggerConditions"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value[1] = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 加载执行动作
  function loadExecuteActions() {
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm
    };

    http
      .post(changeHttpLink("/api/Event/ExecuteActions"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value[2] = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 打开对话框
  function openDialog(type = "新增", row = {}) {
    const result = addDialog({
      title: `${type}事件`,
      props: {
        form: cloneDeep(row),
        type
      },
      width: "500px",
      draggable: true,
      contentRenderer: () => editForm
    });

    if (result && typeof result.then === "function") {
      result.then(() => {
        onSearch();
      });
    } else {
      onSearch();
    }
  }

  // 处理删除
  function handleDelete(row) {
    ElMessageBox.confirm(`是否确认删除ID为${row.id}的这条数据`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Event/Delete"), {
            data: { id: row.id }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`删除成功`, { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const ids = curSelected.map(item => item.id);

    ElMessageBox.confirm(`是否确认删除选中的${ids.length}条数据`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Event/BatchDelete"), {
            data: { ids }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`删除成功`, { type: "success" });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 处理选择变化
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 取消选择
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 处理分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  // 处理当前页码变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 处理更新
  function handleUpdate(row) {
    console.log("更新操作", row);
  }

  // 检测设备
  function deviceDetection() {
    return window.innerWidth < 768;
  }

  // 初始加载
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
